package finedev.work.vennue;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

public class LoginManager extends AsyncTask<String, Void, Integer> {
	
	public static HashMap<String, String> mHashMapResult = null;

	private ProgressDialog mProgressDialog;
	private LoginActivity mActivity;
	private String responseStr;

	public LoginManager(LoginActivity activity, ProgressDialog progressDialog )
	{
		this.mActivity = activity;
		this.mProgressDialog = progressDialog;
	}

	@Override
	protected void onPreExecute()
	{
		mProgressDialog.show();
	}

	@Override
	protected Integer doInBackground(String... arg0) 
	{
		String result = "";
		int responseCode = 0;
		try 
		{
			HttpClient client = new DefaultHttpClient();
			HttpPost httppost = new HttpPost( arg0[0]);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        	nameValuePairs.add(new BasicNameValuePair("user_id", arg0[1]));
	        	nameValuePairs.add(new BasicNameValuePair("passwd", arg0[2]));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response;
			response = client.execute( httppost );
			HttpEntity resEntity = response.getEntity();
			responseCode = response.getStatusLine().getStatusCode();
			responseStr = EntityUtils.toString(resEntity);
			
		}
		catch (Exception e) {
			responseCode = 408;
			e.printStackTrace();
		}
		
		return responseCode;
	}

	@Override
	protected void onPostExecute(Integer headerCode)
	{
		mProgressDialog.dismiss();
		Log.i("LoginManager", "headerCode = " + headerCode );
		if(headerCode >= 200 && headerCode <300)
			try {
				mActivity.ReceiveSuccess( responseStr );
			} catch (JsonParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JsonMappingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		else
			mActivity.ReceiveFail("");
	}

}
